package logic

import (
	"context"
	"encoding/json"
	"manuscript-service/manuscriptrpc/internal/svc"
	"manuscript-service/manuscriptrpc/manuscriptrpc"
	"manuscript-service/models/cache"
	"manuscript-service/models/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ManuscriptListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManuscriptListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManuscriptListLogic {
	return &ManuscriptListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 列表
func (l *ManuscriptListLogic) ManuscriptList(in *manuscriptrpc.ManuscriptListRequest) (*manuscriptrpc.ManuscriptListResponse, error) {
	// todo: add your logic here and delete this line

	var manuscriptList []*manuscriptrpc.ManuscriptList

	result, _ := cache.Rdb.Get(l.ctx, "manuscriptList").Result()

	if result == "" {
		manuscriptList = mysql.ManuscriptList(mysql.DB, manuscriptList)

		marshal, _ := json.Marshal(manuscriptList)

		cache.Rdb.Set(l.ctx, "manuscriptList", marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &manuscriptList)
	}

	return &manuscriptrpc.ManuscriptListResponse{
		List: manuscriptList,
	}, nil
}
